package io.github.jieblog.juc.day3;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * Created by jie on 2017/3/16.
 * java 多线程之mapReduce
 */
public class CountTask extends RecursiveTask<Long> {
    /**
     * 分片大小
     */
    private static final int THRESHOLD = 10;
    private Long start;
    private Long end;

    public CountTask(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0L;
        boolean canCompute = (end - start) > THRESHOLD;
        if (canCompute) {
            for (long i = start; i <= end; i++)
                sum += i;
        } else {//继续分片
            long step = (start + end) / 10;
            ArrayList<CountTask> countTasks = new ArrayList<CountTask>();
            long position = start;
            for (int i = 0; i < 10; i++) {
                long lastOne = position + step;
                if (lastOne > end) lastOne = end;
                CountTask countTask = new CountTask(position, lastOne);
                position += step + 1;
                countTasks.add(countTask);
                countTask.fork();
            }

            for (CountTask t : countTasks)
                sum += t.join();
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask task = new CountTask(0L, 100L);
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        try {
            Long resultNum = result.get();
            System.out.println(resultNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
